<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Models\BaseModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Cache;

class OpenShopOrganizationManageUserModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'open_shop_organization_manage_users';

    protected $fillable = [
        'manageId',
        'userId',
        'name',
        'type',
        'addressCodes',
        'isDeleted',
    ];

    const TYPE_PROVINCE_DEVELOP           = 6;  // 省区开发
    const TYPE_CITY_MANAGER               = 7;  // 城市经理 - 运营城市经理
    const TYPE_INCREASE_MANAGER           = 8;  // 门店增长顾问 - 区域配置的督导
    const TYPE_CHECK_MANAGER              = 9;  // 门店稽核顾问
    const TYPE_SITE_SELECTION_DEVELOPMENT = 10; // 选址开发
    const TYPE_SOLICIT_BUSINESS           = 11; // 招商人员
    const TYPE_DEVELOP_CITY_MANAGER       = 12; // 开发城市经理

    public function manageRel()
    {
        return $this->belongsTo(OpenShopOrganizationManageModel::class, 'manageId', 'id');
    }

    public function getAddressCodesArrAttribute(): array
    {
        $arr = json_decode($this->addressCodes ?? '', true);
        if (!$arr) {
            return [];
        }

        foreach ($arr as $k => &$v) {

            $e = explode('-', $v);

            $v = [
                'provinceCode' => (string)($e[0] ?? ''),
                'cityCode'     => (string)($e[1] ?? ''),
                'regionCode'   => (string)($e[2] ?? ''),
            ];

            if ($this->type == self::TYPE_CITY_MANAGER) {
                unset($arr[$k]['regionCode']);
            }
        }

        return $arr;
    }

    public function getData(int $manageId, int $type): array
    {
        $data = OpenShopOrganizationManageUserModel::query()
                                                  ->where('manageId', $manageId)
                                                  ->where('type', $type)
                                                  ->select('userId', 'name', 'addressCodes', 'type')
                                                  ->get()
                                                  ->map(function ($item) {
                                                      return [
                                                          'userId'          => $item->userId,
                                                          'name'            => $item->name,
                                                          'addressCodesArr' => $item->addressCodesArr,
                                                      ];
                                                  })->toArray();

        $userIds = array_column($data, 'userId');
        if ($userIds && $type == OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER) {// 督导 获取关联的门店

            // 负责区域
            $relationProvinceCodes = OpenShopOrganizationRegionMappingModel::query()
                ->where('manageId', $manageId)
                ->pluck('provinceCode')
                ->toArray();

            $childOrderNo = OpenShopAddressModel::query()
                ->whereIn('provinceCode', $relationProvinceCodes)
                ->select('orderNo');

            // 根据负责区域查询对应订单
            $childMainProcessIds = OpenShopMainProcessModel::query()
                ->whereRaw('orderNo in (' . BaseModel::toSqlWithParam($childOrderNo) . ')')
                ->select('id');
            $shopRelData = OpenShopOrderManagerModel::getShopIdByUid($userIds, $childMainProcessIds);
            foreach ($data as &$v) {
                $v['shopIds'] = $shopRelData[$v['userId']] ?? [];
            }
        }
        return $data;
    }

    /**
     * @return HasOne
     */
    public function fsUserRel(): HasOne
    {
        return $this->hasOne(KmsUser::class, "rmsUserId", "userId")->where('isExited', KmsUser::IS_EXITED_OFF);
    }
}
